package com.example.zhinongbao.adapter;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.zhinongbao.R;
import com.example.zhinongbao.provider.ZhinongbaoContract;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import de.hdodenhof.circleimageview.CircleImageView;

public class FriendCircleAdapter extends RecyclerView.Adapter<FriendCircleAdapter.ViewHolder> {

    private final Context context;
    private Cursor cursor;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());

    public FriendCircleAdapter(Context context, Cursor cursor) {
        this.context = context;
        this.cursor = cursor;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context)
                .inflate(R.layout.item_friend_circle, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        if (!ensureCursorPosition(position)) {
            return;
        }

        try {
            // 获取动态ID
            long postId = getCursorLong(ZhinongbaoContract.FriendCircle._ID);

            // 获取用户信息
            String userName = getCursorString(ZhinongbaoContract.FriendCircle.COLUMN_USER_NAME);
            String avatarUrl = getCursorString(ZhinongbaoContract.FriendCircle.COLUMN_USER_AVATAR);
            long createTime = getCursorLong(ZhinongbaoContract.FriendCircle.COLUMN_CREATE_TIME);

            // 获取动态内容
            String content = getCursorString(ZhinongbaoContract.FriendCircle.COLUMN_CONTENT);
            byte[] imageData = getCursorBlob(ZhinongbaoContract.FriendCircle.COLUMN_IMAGE_DATA);

            // 获取互动数据
            int likeCount = getCursorInt(ZhinongbaoContract.FriendCircle.COLUMN_LIKE_COUNT);
            int commentCount = getCursorInt(ZhinongbaoContract.FriendCircle.COLUMN_COMMENT_COUNT);

            // 绑定数据到视图
            bindDataToViews(holder, userName, avatarUrl, createTime, content, imageData, likeCount, commentCount);

            // 设置更多按钮点击事件
            holder.btnMore.setOnClickListener(v -> showPopupMenu(v, position, postId));

        } catch (Exception e) {
            Log.e("FriendCircleAdapter", "Error binding view holder", e);
            showErrorToast();
        }
    }

    private boolean ensureCursorPosition(int position) {
        if (cursor == null || cursor.isClosed()) {
            Log.w("FriendCircleAdapter", "Cursor is null or closed");
            return false;
        }
        if (!cursor.moveToPosition(position)) {
            Log.w("FriendCircleAdapter", "Could not move cursor to position " + position);
            return false;
        }
        return true;
    }

    private String getCursorString(String columnName) {
        int index = cursor.getColumnIndex(columnName);
        return index != -1 ? cursor.getString(index) : "";
    }

    private int getCursorInt(String columnName) {
        int index = cursor.getColumnIndex(columnName);
        return index != -1 ? cursor.getInt(index) : 0;
    }

    private long getCursorLong(String columnName) {
        int index = cursor.getColumnIndex(columnName);
        return index != -1 ? cursor.getLong(index) : 0L;
    }

    private byte[] getCursorBlob(String columnName) {
        int index = cursor.getColumnIndex(columnName);
        return index != -1 ? cursor.getBlob(index) : null;
    }

    private void bindDataToViews(ViewHolder holder, String userName, String avatarUrl, long createTime,
                                 String content, byte[] imageData, int likeCount, int commentCount) {
        // 用户信息
        holder.tvUserName.setText(userName);
        holder.tvPostTime.setText(formatTime(createTime));

        // 动态内容
        holder.tvContent.setText(content);

        // 互动数据
        holder.tvLikeCount.setText(formatCount(likeCount));
        holder.tvCommentCount.setText(formatCount(commentCount));

        // 加载头像
        loadAvatar(holder.civAvatar, avatarUrl);

        // 处理动态图片
        handlePostImage(holder.ivPostImage, imageData);

        // 设置点赞和评论点击监听
        setupClickListeners(holder, likeCount);
    }

    private String formatTime(long timestamp) {
        return dateFormat.format(new Date(timestamp));
    }

    private String formatCount(int count) {
        return count > 999 ? "999+" : String.valueOf(count);
    }

    private void loadAvatar(CircleImageView imageView, String avatarUrl) {
        if (avatarUrl == null || avatarUrl.isEmpty()) {
            imageView.setImageResource(R.drawable.ic_default_avatar);
            return;
        }

        Glide.with(context)
                .load(avatarUrl)
                .placeholder(R.drawable.ic_default_avatar)
                .error(R.drawable.ic_default_avatar)
                .into(imageView);
    }

    private void handlePostImage(ImageView imageView, byte[] imageData) {
        if (imageData != null && imageData.length > 0) {
            imageView.setVisibility(View.VISIBLE);
            Glide.with(context)
                    .load(imageData)
                    .centerCrop()
                    .into(imageView);
        } else {
            imageView.setVisibility(View.GONE);
        }
    }

    private void setupClickListeners(ViewHolder holder, int likeCount) {
        holder.btnLike.setOnClickListener(v -> {
            // 点赞逻辑
            int newLikeCount = likeCount + 1;
            holder.tvLikeCount.setText(formatCount(newLikeCount));
            Toast.makeText(context, "点赞成功", Toast.LENGTH_SHORT).show();
        });

        holder.btnComment.setOnClickListener(v -> {
            // 评论逻辑
            Toast.makeText(context, "跳转评论", Toast.LENGTH_SHORT).show();
        });
    }

    private void showPopupMenu(View anchorView, int position, long postId) {
        PopupMenu popupMenu = new PopupMenu(context, anchorView);
        popupMenu.getMenuInflater().inflate(R.menu.post_options_menu, popupMenu.getMenu());

        // 根据动态所有者判断是否显示删除按钮
        boolean isOwner = checkIfCurrentUserIsOwner(position);
        popupMenu.getMenu().findItem(R.id.menu_delete).setVisible(isOwner);

        popupMenu.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.menu_delete) {
                showDeleteConfirmDialog(postId, position);
                return true;
            } else if (itemId == R.id.menu_report) {
                reportPost(position);
                return true;
            } else if (itemId == R.id.menu_share) {
                sharePost(position);
                return true;
            }
            return false;
        });

        // 显示菜单
        popupMenu.show();
    }

    private boolean checkIfCurrentUserIsOwner(int position) {
        if (cursor != null && cursor.moveToPosition(position)) {
            String postUserId = getCursorString(ZhinongbaoContract.FriendCircle.COLUMN_USER_ID);
            String currentUserId = "user123"; // 替换为获取当前用户ID的实际方法
            return postUserId.equals(currentUserId);
        }
        return false;
    }

    private void showDeleteConfirmDialog(long postId, int position) {
        new AlertDialog.Builder(context)
                .setTitle("确认删除")
                .setMessage("确定要删除这条动态吗？")
                .setPositiveButton("删除", (dialog, which) -> deletePost(postId, position))
                .setNegativeButton("取消", null)
                .show();
    }

    private void deletePost(long postId, int position) {
        try {
            Uri deleteUri = ContentUris.withAppendedId(
                    ZhinongbaoContract.FriendCircle.CONTENT_URI, postId);
            int deletedRows = context.getContentResolver().delete(
                    deleteUri, null, null);

            if (deletedRows > 0) {
                notifyItemRemoved(position);
                Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e("FriendCircleAdapter", "Delete post failed", e);
            Toast.makeText(context, "删除时发生错误", Toast.LENGTH_SHORT).show();
        }
    }

    private void reportPost(int position) {
        Toast.makeText(context, "举报已提交，我们将尽快处理", Toast.LENGTH_SHORT).show();
        // 这里可以添加实际的举报逻辑
    }

    private void sharePost(int position) {
        if (cursor != null && cursor.moveToPosition(position)) {
            String content = getCursorString(ZhinongbaoContract.FriendCircle.COLUMN_CONTENT);

            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, "分享农友圈动态：" + content);
            context.startActivity(Intent.createChooser(shareIntent, "分享到"));
        }
    }

    private void showErrorToast() {
        Toast.makeText(context, "加载动态失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int getItemCount() {
        return cursor != null ? cursor.getCount() : 0;
    }

    public void swapCursor(Cursor newCursor) {
        if (cursor != null) {
            cursor.close();
        }
        cursor = newCursor;
        notifyDataSetChanged();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        CircleImageView civAvatar;
        TextView tvUserName;
        TextView tvPostTime;
        TextView tvContent;
        ImageView ivPostImage;
        Button btnLike;
        Button btnComment;
        TextView tvLikeCount;
        TextView tvCommentCount;
        ImageView btnMore;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            civAvatar = itemView.findViewById(R.id.civAvatar);
            tvUserName = itemView.findViewById(R.id.tvUserName);
            tvPostTime = itemView.findViewById(R.id.tvPostTime);
            tvContent = itemView.findViewById(R.id.tvContent);
            ivPostImage = itemView.findViewById(R.id.ivPostImage);
            btnLike = itemView.findViewById(R.id.btnLike);
            tvLikeCount = itemView.findViewById(R.id.tvLikeCount);
            tvCommentCount = itemView.findViewById(R.id.tvCommentCount);
            btnMore = itemView.findViewById(R.id.btnMore);
        }
    }
}